// shopCart/pages/cart/cart.js
var http = require('../../utils/https');
Page({

  /**
   * 页面的初始数据
   */
  data: {

    userInof: {},
    cart: [],
    cartList: [{
        id: 0,
        title: ' ',
        spec: '',
        price: 0,
        quantity: 1,
        checked: false,
        image: '',
         cartCount: 0
      }
    
    ],
    allChecked: false,
    totalPrice: 0.00,
    checkedCount: 0,
    isManaging: false
  },

  // 切换管理模式
  toggleManage() {
    this.setData({
      isManaging: !this.data.isManaging
    });
  },
  // 单个删除
  onDeleteSingle(e) {
    const id = e.currentTarget.dataset.id;
    console.log(id);
    var cart = this.data.cart
    for (var i = 0; i < cart.length; i++) {
      if (cart[i].id == id) {
        cart.splice(i, 1)
        break
      }
    }

    http.DELETE(`/order/items/${id}`, {}, function (res) {
      if (res.code === 200) {
        console.log("删除成功");
      }
    }, function (err) {
      console.error('失败:', err);
    });
    this.setData({
      cart: cart
    })

    this.updateCart(cart);
  },
  // 单个商品选择
  onItemCheck(e) {
    const id = e.currentTarget.dataset.id; // 商品id
    console.log(e);
    var t = 0
    if (e.detail) {
      t = 1
    }
    // t 是 商品是否被选中
    var cart = this.data.cart
    for (var i = 0; i < cart.length; i++) {
      if (cart[i].productId == id) {
        cart[i].checked = t
        break
      }
    }

    http.PUT('/order/items/updateCart', {
      userId: this.data.userInof.userId,
      productId: id,
      checked: t
    }, function (res) {
      if (res.code === 200) {
        console.log("成功");
      } else {
        // 失败
      }
    }, function (err) {
      console.error('失败:', err);
    });


    this.setData({
      cart: cart
    })

    this.updateCart(cart);
  },

  // 全选
  onAllCheck(e) {
    const checked = e.detail == true ? 1 : 0;
    var cart = this.data.cart
    var userId = this.data.userInof.userId
    for (var i = 0; i < cart.length; i++) {
      cart[i].checked = checked
      http.PUT('/order/items/updateCart', {
        userId:userId,
        productId: cart[i].productId,
        checked: checked
      }, function (res) {
        if (res.code === 200) {
          console.log("成功");
        } else {
          // 失败
        }
      }, function (err) {
        console.error('失败:', err);
      });
    }
    this.setData({
      cart: cart
    })

    this.updateCart(cart);
  },

  // 格式化日期为 yyyy-MM-dd 格式
  formatDateForBackend(date) {
    const year = date.getFullYear();
    // 月份从0开始，需要+1，且不足两位补0
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    // 日期不足两位补0
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 数量变化
  onQuantityChange(e) {
    console.log(e);
    var quantity = e.detail // 购物车里的数量
    var productId = e.currentTarget.dataset.id // 商品的id
    var cart = this.data.cart
    for (var i = 0; i < cart.length; i++) {
      if (cart[i].productId == productId) {
        cart[i].quantity = quantity
        break;
      }
    }
    this.setData({
      cart: cart
    })

    http.PUT('/order/items/UIdAndPId', {
      productId: productId,
      quantity: quantity,
      userId: this.data.userInof.userId
    }, function (res) {
      console.log('成功:', res);
    }, function (err) {
      console.error('失败:', err);
    });

    this.updateCart(cart) // 更新细节
  },

  // 删除选中商品
  onDelete() {
    var ids = []
    var cart = this.data.cart
    for (var i = 0; i < cart.length; i++) {
      if (cart[i].checked == 1) {
        ids.push(cart[i].id)
      }
    }
    const newItems = this.data.cart.filter(item => !ids.includes(item.id));

    http.DELETE(`/order/items/${ids}`, {}, function (res) {
      if (res.code === 200) {
        console.log("全部删除成功");
      }
    }, function (err) {
      console.error('失败:', err);
    });

    // 更新数据
    this.setData({
      cart: newItems
    });
    this.updateCart(newItems)

  },

  // 结算
  onCheckout() {
    var cart = this.data.cart
    var order = []
    for (var i = 0; i < cart.length; i++) {
      if (cart[i].checked == 1) {
        order.push(cart[i])
      }
    }

    console.log(order);
    const currentDate = new Date();
    const formattedDate = this.formatDateForBackend(currentDate);
    wx.navigateTo({
      url: '/shopCart/pages/realorder/realorder?totalPrice='+this.data.totalPrice+'&order='+JSON.stringify(order),
      
    })
  },

  // 更新全选、总价、数量
  updateCart(cart) {
      var t = 0 // 判断是否全选
      var money = 0 // 商品总计金额
      var count = 0 // 勾选数量
      var totalCount = 0 // 购物车商品总数量（不管是否勾选）

      if (cart.length > 0) {
          for (var i = 0; i < cart.length; i++) {
              t += cart[i].checked
              totalCount += cart[i].quantity // 👈 所有商品数量累加

              if (cart[i].checked == 1) {
                  money += cart[i].product.price * cart[i].quantity
                  count += cart[i].quantity
              }
          }
          this.setData({
              totalPrice: money,
              allChecked: t == cart.length,
              checkedCount: count,
              cartCount: totalCount // 👈 更新购物车数量
          })

      } else {
          this.setData({
              checkedCount: 0,
              totalPrice: 0,
              allChecked: false,
              cartCount: 0 // 👈 购物车清空
          })
      }
  },
  onLoad(options) {
    var userInof = wx.getStorageSync('userInfo')
    if (userInof == '' || userInof == null || userInof.userId == null || userInof.userId == null) {
      wx.showToast({
        title: '请登录',
      })
      wx.redirectTo({
        url: '/index/pages/mzhLogin/mzhLogin',
      })
    } else {
      var that = this
      that.setData({
        userInof: userInof
      })
      var userId = userInof.userId
      http.GET(`/order/items/user/${userId}`, {}, function (res) {
        if (res.code === 200) {
          // console.log('成功:', res);
          that.setData({
            cart: res.data
          })
          that.updateCart(that.data.cart)
          console.log(that.data.cart);
        } else {
          wx.showToast({
            title: '认证过期，重新登录',
            duration: 1500
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '/index/pages/mzhLogin/mzhLogin',
            })
          }, 1500);

          console.log(res);
        }

      }, function (err) {
        console.error('失败:', err);
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var userInof = wx.getStorageSync('userInfo')
    if (userInof == '' || userInof == null || userInof.userId == null || userInof.userId == null) {
      wx.showToast({
        title: '请登录',
      })
      wx.redirectTo({
        url: '/index/pages/mzhLogin/mzhLogin',
      })
    } else {
      var that = this
      that.setData({
        userInof: userInof
      })
      var userId = userInof.userId
      http.GET(`/order/items/user/${userId}`, {}, function (res) {
        if (res.code === 200) {
          // console.log('成功:', res);
          that.setData({
            cart: res.data
          })
          that.updateCart(that.data.cart)
          console.log(that.data.cart);
        } else {
          wx.showToast({
            title: '认证过期，重新登录',
            duration: 1500
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '/index/pages/mzhLogin/mzhLogin',
            })
          }, 1500);

          console.log(res);
        }

      }, function (err) {
        console.error('失败:', err);
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})